package cn.cy.service.imp;

import cn.cy.domain.Const.LowerConst;
import cn.cy.domain.StepResult;
import cn.cy.service.LowerComputer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


/**
 * @Author: Xucranger
 * @Date: 22/5/1 15:07
 * @Des: 我没做多线程啊，求助
 */
@Slf4j
@Service
public class LowerComputerImp implements LowerComputer {
    //请求地址
    public static final String url = LowerConst.url;
    //格子移动的距离
    public static final Integer xunit = LowerConst.xunit;
    public static final Integer yunit = LowerConst.yunit;

    /**
     * @author: Xucranger
     * @description: 发送指令，id是电机名称，step是绝对步数
     * @date: 22/5/1 16:01
     * @param step,id
     * @return result
     */
    @Async("sendcmd")
    public  Boolean sendcmd(Integer id, Integer step) {
        String logstr = "move motor"+id.toString()+" to "+step.toString();
        log.info(logstr);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",id);
        jsonObject.put("step",step);
        String data = JSON.toJSONString(jsonObject);
        log.info(data);

        JSONObject result = sendPostWithJson(url,data);
        if(!result.getBoolean("success")){
            return true;
        }
        return false;
    }

    /**
     * @author: Xucranger
     * @description: 发送http请求
     * @date: 22/5/1 15:14
     * @param url,data
     * @return response
     */
    public JSONObject sendPostWithJson(String url, String data) {

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        String response = "";
        JSONObject result = new JSONObject();
        try {
            StringEntity s = new StringEntity(data,"UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                response = EntityUtils.toString(res.getEntity());// 返回json格式：
                result = JSON.parseObject(response);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }


    /**
     * @author: Xucranger
     * @description: 初始化机器位置
     * @date: 22/5/1 16:00
     * @return result
     */
    @Override
    public StepResult init() {
        //xyz三轴归位
        Boolean x = sendcmd(1,0);
        Boolean y = sendcmd(2,0);
        Boolean z = sendcmd(3,0);
        if(x&&y&&z){
            return StepResult.succ("init");
        }

        return StepResult.fail("init");
    }


    /**
     * @author: Xucranger
     * @description: 移动抽屉
     * @date: 22/5/1 16:08
     * @return result
     */
    @Override
    public StepResult movedrawer(Integer step) {
        //a轴移动
        Boolean a = sendcmd(4,step);
        if(a){
            return StepResult.succ("movedrawer"+step.toString());
        }
        return StepResult.fail("movedrawer"+step.toString());
    }

    /**
     * @author: Xucranger
     * @description: 到达格子位置
     * @date: 22/5/1 16:11
     * @param x,y
     * @return result
     */
    @Override
    public StepResult arriveto(Integer x, Integer y) {
        Integer xstep = x*xunit;
        Integer ystep = y&yunit;
        Boolean xres = sendcmd(1,xstep);
        Boolean yres = sendcmd(2,ystep);
        if(xres&&yres){
            return StepResult.succ("arriveto");
        }
        return StepResult.fail("arriveto");
    }
}
